// src/stores/user.js
// 用户状态管理

import { ref, reactive } from 'vue'

// 用户状态
const user = reactive({
  isLoggedIn: false,
  id: null,
  username: '',
  nickname: '',
  avatar: '',
  token: ''
})

// 登录
export function loginUser(userData) {
  user.isLoggedIn = true
  user.id = userData.id
  user.username = userData.username || userData.nickname
  user.nickname = userData.nickname
  user.avatar = userData.avatar
  user.token = userData.token
  
  // 存储到localStorage
  localStorage.setItem('userInfo', JSON.stringify({
    id: userData.id,
    username: userData.username || userData.nickname,
    nickname: userData.nickname,
    avatar: userData.avatar,
    token: userData.token
  }))
}

// 退出登录
export function logoutUser() {
  user.isLoggedIn = false
  user.id = null
  user.username = ''
  user.nickname = ''
  user.avatar = ''
  user.token = ''
  
  // 清除localStorage
  localStorage.removeItem('userInfo')
}

// 从localStorage恢复用户状态
export function restoreUserFromStorage() {
  const userInfo = localStorage.getItem('userInfo')
  if (userInfo) {
    try {
      const userData = JSON.parse(userInfo)
      loginUser(userData)
    } catch (error) {
      console.error('恢复用户状态失败:', error)
      localStorage.removeItem('userInfo')
    }
  }
}

// 获取当前用户ID
export function getCurrentUserId() {
  return user.id
}

// 导出用户状态
export { user }